package api;

import com.alibaba.fastjson.JSON;
import http.RequestSender;
import http.Response;
import myException.InputFormatException;
import myException.ServerConnectException;
import utils.AESUtils;
import utils.KeyUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 服务端UserAction的方法调用
 */
public class UserApi {

    public final static String USER_ACTION_PATH = "/user";

    public final static String LOGIN = USER_ACTION_PATH + "/login";
    public final static String REGISTER = USER_ACTION_PATH + "/register";
    public final static String QUERY_USER_NAME = USER_ACTION_PATH + "/query_user_name";

    public static Response login(String account, String pwd) throws ServerConnectException, InputFormatException{
        try {
            String aesPwd = AESUtils.encrypt(pwd, KeyUtils.USER_AES_KEY);
            Map<String, String> paramsMap = new HashMap<>();
            paramsMap.put("account", account);
            paramsMap.put("pwd", aesPwd);
            return RequestSender.sendPostRequest(LOGIN, JSON.toJSONString(paramsMap));
        } catch (ServerConnectException e) {
            throw new ServerConnectException();
        } catch (Exception e) {
            throw new InputFormatException();
        }
    }

    public static Response register(String account, String pwd) throws ServerConnectException, InputFormatException {
        try {
            String aesPwd = AESUtils.encrypt(pwd, KeyUtils.USER_AES_KEY);
            Map<String, String> paramsMap = new HashMap<>();
            paramsMap.put("account", account);
            paramsMap.put("pwd", aesPwd);
            return RequestSender.sendPostRequest(REGISTER, JSON.toJSONString(paramsMap));
        } catch (ServerConnectException e) {
            throw new ServerConnectException();
        } catch (Exception e) {
            throw new InputFormatException();
        }
    }

    public static Response query_user_name(long user_id, long query_user) throws ServerConnectException {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("user_id", String.valueOf(user_id));
        paramsMap.put("query_user", String.valueOf(query_user));
        return RequestSender.sendPostRequest(QUERY_USER_NAME, JSON.toJSONString(paramsMap));
    }
}
